package com.tangtang.hystrix.provider.command;

import com.alibaba.fastjson.JSONObject;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.tangtang.hystrix.provider.utils.HttpClientUtils;
import com.tangtang.hystrix.provider.vo.ProductVO;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

public class ProductObservableCommand extends HystrixObservableCommand<ProductVO> {


    private Long id;
    public ProductObservableCommand(Long id){
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("order"))
                .andCommandKey(HystrixCommandKey.Factory.asKey("proudct"));

                //.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("PERF")//不支持
        this.id = id;
    }

    @Override
    protected Observable<ProductVO> construct() {
       return Observable.unsafeCreate(new Observable.OnSubscribe<ProductVO>() {
            @Override
            public void call(Subscriber<? super ProductVO> observer) {
                try {
                    if (!observer.isUnsubscribed()) {
                        String request = HttpClientUtils.sendGetRequest("http://127.0.0.1:8086/api/v1/product/"+id);
                        ProductVO productVO  =  JSONObject.parseObject(request, ProductVO.class);
                        observer.onNext(productVO);
                        observer.onCompleted();
                    }
                } catch (Exception e) {
                    observer.onError(e);
                }
            }
        } ).subscribeOn(Schedulers.io());
    }
}
